package cn.edu.nju.software.zp13.assignment6.client;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import javax.xml.soap.SOAPMessage;

import cn.edu.nju.software.zp13.assignment5.service.soapMessage.SOAPMsgWriter;
import cn.edu.nju.software.zp13.assignment6.util.InputStreamToStr;

/**
 * send SOAPMessage to a specific URL.
 * 
 * @author Ivan
 *
 */
public class Sender {
	private HttpURLConnection httpConn;

	/**
	 * POST a SOAP msg to a specific URL.
	 * 
	 * @param url post to.
	 * @param msg a SOAPMessage Object. 
	 * @return reposne encode to a string.
	 */
	public String postMsg(String url, SOAPMessage msg) {
		initConn(url);
		try {
			httpConn.setRequestMethod("POST");
		} catch (ProtocolException e) {
			e.printStackTrace();
		}
		InputStream inputStream = null;
		try {
			// write soap msg to outputStream.
			SOAPMsgWriter.writeMsg(msg, httpConn.getOutputStream());
			System.out.println("============send soap message:");
			SOAPMsgWriter.writeMsg(msg, System.out);
			inputStream = httpConn.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return InputStreamToStr.run(inputStream, "utf-8");
	}

	private void initConn(String url) {
		try {
			httpConn = (HttpURLConnection) new URL(url).openConnection();
		} catch (IOException e) {
			e.printStackTrace();
		}
		httpConn.setDoOutput(true);
		httpConn.setDoInput(true);
		httpConn.setUseCaches(false);
	}
}
